package netty.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/5/29 0029
 * Time: 上午 11:44
 * To change this template use File | Settings | File Templates.
 */
public class MyChatClient {

    public static void main(String[] args) {

        ExecutorService executors =  Executors.newFixedThreadPool(10);
        for (int i = 0; i <10 ; i++) {
            executors.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        sendMsg();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            executors.shutdown();
            while (!executors.isTerminated()){}
        }
    }

    private static void sendMsg() throws InterruptedException {
        NioEventLoopGroup client = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(client);

        bootstrap.channel(NioSocketChannel.class)
                .handler(new ChatClientInitializer());

        try {

                Channel channel = null;

                    channel = bootstrap.connect("localhost", 8080).sync().channel();

                        //  localhost.channel().closeFuture().sync();
//            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//            for (;;){
                        //channel.writeAndFlush(br.readLine()+"\r\n");
                        //}
                        channel.writeAndFlush("xxxxxxxxxxxxxx"+"\r\n");
                        try {
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        channel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            client.shutdownGracefully();
        }
    }
}
